package com.itlong.cloud.property.service.impl;


import com.itlong.cloud.POJO.DTO.property.PropertyLadderFeeDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyRuleGetDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyFeeRuleDTO;
import com.itlong.cloud.POJO.PO.FeeRuleInfoPO;
import com.itlong.cloud.POJO.PO.LadderFeeInfoPO;
import com.itlong.cloud.POJO.VO.property.PropertyLadderFeeVO;
import com.itlong.cloud.POJO.VO.property.PropertyRuleDetailVO;
import com.itlong.cloud.POJO.VO.property.PropertyRuleVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.property.dao.IPropertyRuleDao;
import com.itlong.cloud.property.service.IPropertyPaymentManageService;
import com.itlong.cloud.property.service.IPropertyRuleService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <desc>
 *     收费管理-收费规则处理接口实现.
 * </desc>
 *
 * @createDate 2018-08-09
 */
@Service
public class PropertyRuleServiceImpl implements IPropertyRuleService {

    @Autowired
    IPropertyRuleDao iPropertyRuleDao;

    @Autowired
    IPropertyPaymentManageService iPropertyPaymentManageService;

    /**
     * <desc>
     *      分页查询收费规则
     * <desc/>
     *
     * @param propertyRuleGetDTO 分页查询收费规则DTO
     * @return
     * @author Qiang.S
     * @createDate 2018-08-09
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<PropertyRuleVO> getRuleByPage(PropertyRuleGetDTO propertyRuleGetDTO) throws Exception {
        //分页对象
        Page<PropertyRuleVO> page = new Page<>();
        //将DTO转换为Map
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(propertyRuleGetDTO, page);

        //填充返回数据集
        page.setRows(iPropertyRuleDao.getRuleByPage(params), iPropertyRuleDao.getCount(params));
        return page;
    }

    /**
     * <desc>
     *      根据收费类型查询收费规则
     * <desc/>
     *
     * @param projectId 项目编号
     * @param feeType 收费类型：1抄表费 2物业费 3维修费 4停车费
     * @param feeCycle 收费周期：1月 2季度 3年
     * @return MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/15
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<PropertyRuleVO> getRuleByFeeType(String projectId,String feeType,String feeCycle) throws Exception {
        return iPropertyRuleDao.getRuleByFeeType(projectId,feeType,feeCycle);
    }

    /**
     * <desc>
     *     查询收费规则详情
     * <desc/>
     *
     * @param  feeRuleId  分页查询收费规则记录
     * @param  projectId  项目编号
     * @return  MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/09
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public PropertyRuleDetailVO getRuleDetail(String feeRuleId, String projectId) throws Exception {
        PropertyRuleDetailVO propertyRuleDetailVO = iPropertyRuleDao.getRuleDetail(feeRuleId,projectId);
        if (propertyRuleDetailVO != null) {
            List<PropertyLadderFeeVO> ladderFeeList = iPropertyRuleDao.getLadderFee(feeRuleId);
            propertyRuleDetailVO.setLadderFeeList(ladderFeeList);
        }
        return propertyRuleDetailVO;
    }

    /**
     * <desc>
     *     新增收费规则
     * <desc/>
     *
     * @param  propertyFeeRuleDTO  收费规则信息
     * @return  MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/09
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer saveRule(PropertyFeeRuleDTO propertyFeeRuleDTO) throws Exception {
        FeeRuleInfoPO feeRuleInfoPO = new FeeRuleInfoPO();
        BeanUtils.copyProperties(propertyFeeRuleDTO, feeRuleInfoPO);
        Date createTime = new Date();
        feeRuleInfoPO.setFeeRuleId(LogicIdUtil.bussinessId());

        //当阶梯收费信息有数据并且计量方式为2阶梯收费时
        if (propertyFeeRuleDTO.getLadderFeeList().size() > 0 && "2".equals(feeRuleInfoPO.getMeasureType())) {
            //批量保存阶梯收费信息
            List<Map<String,Object>> batchParams = new ArrayList<>();
            for (int i=0;i<propertyFeeRuleDTO.getLadderFeeList().size();i++)
            {
                PropertyLadderFeeDTO propertyLadderFeeDTO = propertyFeeRuleDTO.getLadderFeeList().get(i);
                LadderFeeInfoPO ladderFeeInfoPO = new LadderFeeInfoPO();
                ladderFeeInfoPO.setFeeId(LogicIdUtil.bussinessId());
                ladderFeeInfoPO.setFeeRuleId(feeRuleInfoPO.getFeeRuleId());
                ladderFeeInfoPO.setOrders(propertyLadderFeeDTO.getOrders());
                ladderFeeInfoPO.setUsageAmountMin(propertyLadderFeeDTO.getUsageAmountMin());
                if (i != propertyFeeRuleDTO.getLadderFeeList().size()-1) {
                    ladderFeeInfoPO.setUsageAmountMax(propertyLadderFeeDTO.getUsageAmountMax());
                }else {
                    ladderFeeInfoPO.setUsageAmountMax(null);
                }
                ladderFeeInfoPO.setPrice(propertyLadderFeeDTO.getPrice());
                ladderFeeInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                ladderFeeInfoPO.setCreateTime(createTime);
                ladderFeeInfoPO.setUpdateTime(null);
                batchParams.add(SqlUtil.durableData(ladderFeeInfoPO, PlatformConstants.TABLE_SAVE));
            }
            iPropertyRuleDao.batchSaveLadderFeeInfo(batchParams);
        }
        feeRuleInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
        feeRuleInfoPO.setCreateTime(createTime);
        feeRuleInfoPO.setUpdateTime(null);
        Map<String, Object> params = SqlUtil.durableData(feeRuleInfoPO, PlatformConstants.TABLE_SAVE);
        for(String key : params.keySet()){
            if (params.get(key) != null && "".equals(params.get(key))) {
                params.put(key,null);
            }
        }
        return iPropertyRuleDao.saveRule(params);
    }

    /**
     * <desc>
     *     判断规则名称是否重复
     * <desc/>
     *
     * @param  ruleName  收费规则名称
     * @param  projectId  项目编号
     * @param  feeRuleId  收费规则ID
     * @return  MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/10/24
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer checkRuleNameRepeat(String ruleName, String projectId, String feeRuleId) throws Exception {
        return iPropertyRuleDao.checkRuleNameRepeat(ruleName,projectId,feeRuleId);
    }

    /**
     * <desc>
     *     更新收费规则
     * <desc/>
     *
     * @param  propertyFeeRuleDTO  收费规则信息
     * @return  MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/09
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer updateRule(PropertyFeeRuleDTO propertyFeeRuleDTO) throws Exception {
        FeeRuleInfoPO feeRuleInfoPO = new FeeRuleInfoPO();
        BeanUtils.copyProperties(propertyFeeRuleDTO, feeRuleInfoPO);
        Date updateTime = new Date();

        //先走删除
        iPropertyRuleDao.deleteLadderFee(feeRuleInfoPO.getFeeRuleId());
        //当阶梯收费信息有数据并且计量方式为2阶梯收费时
        if (propertyFeeRuleDTO.getLadderFeeList().size() > 0 && "2".equals(feeRuleInfoPO.getMeasureType())) {
            //批量保存阶梯收费信息
            List<Map<String,Object>> batchParams = new ArrayList<>();
            for (int i=0;i<propertyFeeRuleDTO.getLadderFeeList().size();i++)
            {
                PropertyLadderFeeDTO propertyLadderFeeDTO = propertyFeeRuleDTO.getLadderFeeList().get(i);
                LadderFeeInfoPO ladderFeeInfoPO = new LadderFeeInfoPO();
                ladderFeeInfoPO.setFeeId(LogicIdUtil.bussinessId());
                ladderFeeInfoPO.setFeeRuleId(feeRuleInfoPO.getFeeRuleId());
                ladderFeeInfoPO.setOrders(propertyLadderFeeDTO.getOrders());
                ladderFeeInfoPO.setUsageAmountMin(propertyLadderFeeDTO.getUsageAmountMin());
                if (i != propertyFeeRuleDTO.getLadderFeeList().size()-1) {
                    ladderFeeInfoPO.setUsageAmountMax(propertyLadderFeeDTO.getUsageAmountMax());
                }else {
                    ladderFeeInfoPO.setUsageAmountMax(null);
                }
                ladderFeeInfoPO.setPrice(propertyLadderFeeDTO.getPrice());
                ladderFeeInfoPO.setStatus(DataStatusEnum.NORMAL.getType());
                ladderFeeInfoPO.setCreateTime(updateTime);
                ladderFeeInfoPO.setUpdateTime(updateTime);
                batchParams.add(SqlUtil.durableData(ladderFeeInfoPO, PlatformConstants.TABLE_SAVE));
            }
            iPropertyRuleDao.batchSaveLadderFeeInfo(batchParams);
        }
        feeRuleInfoPO.setUpdateTime(updateTime);
        Map<String, Object> params = SqlUtil.durableData(feeRuleInfoPO, PlatformConstants.TABLE_UPDATE);
        for(String key : params.keySet()){
            if (params.get(key) != null && "".equals(params.get(key))) {
                params.put(key,null);
            }
        }
        //penalty_percentage,penalty_day,reminder_day,remark  置空
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = (List<Map<String, Object>>) params.get("list");
        if (propertyFeeRuleDTO.getRemark() == null) {
            map = new HashMap<>();
            map.put("columnName","remark");
            map.put("columnValue",null);
            list.add(map);
        }
        if (propertyFeeRuleDTO.getPenaltyDay() == null) {
            map = new HashMap<>();
            map.put("columnName","penalty_day");
            map.put("columnValue",null);
            list.add(map);
        }
        if (propertyFeeRuleDTO.getPenaltyPercentage() == null) {
            map = new HashMap<>();
            map.put("columnName","penalty_percentage");
            map.put("columnValue",null);
            list.add(map);
        }
        if (propertyFeeRuleDTO.getReminderDay() == null) {
            map = new HashMap<>();
            map.put("columnName","reminder_day");
            map.put("columnValue",null);
            list.add(map);
        }
        params.put("list",list);
        int s = iPropertyRuleDao.updateRule(params);
        //更新规则后 重新更新账单
//        iPropertyPaymentManageService.ruleChangeUpdateBill(feeRuleInfoPO.getFeeRuleId());
        return s;
    }

    /**
     * <desc>
     *     删除收费规则
     * <desc/>
     *
     * @param  feeRuleId 收费规则ID
     * @return  MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/08/09
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer deleteRule(String feeRuleId) throws Exception {
        //删除收费信息
        iPropertyRuleDao.deleteRule(feeRuleId);
        //删除阶梯收费信息
        iPropertyRuleDao.deleteLadderFee(feeRuleId);
        return null;
    }

    /**
     * <desc>
     *     查询收费规则是否被绑定
     * <desc/>
     *
     * @param  feeRuleId 收费规则ID
     * @return  MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/09/03
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer deleteRuleCheck(String feeRuleId) throws Exception {
        return iPropertyRuleDao.deleteRuleCheck(feeRuleId);
    }

    /**
     * <desc>
     *     根据账单编号获取最小收费日
     * <desc/>
     *
     * @param  feeId 账单编号
     * @return  MessageVO 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2018/10/25
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public String getMinFeeDay(String feeId) throws Exception {
        return iPropertyRuleDao.getMinFeeDay(feeId);
    }

}
